<?php
/**
 * H5支付.
 */

namespace app\api\service\payment;

use app\common\library\exception\ParameterException;

use app\api\service\ApiPayment;
use app\common\library\exception\OrderException;
use think\Log;
use PhpOffice\PhpSpreadsheet\Exception;

class Npay extends ApiPayment
{
    public function h5pay($order)
    {
        // $bankURL = 'http://47.244.147.2:8088/api/Channels/';
        // $bankURL = 'http://120.24.157.18:7744/api/Channels/';   //测试服务器

        $bankURL = 'http://47.244.147.2:6088/api/Channels/';

        return $this->requestApi($bankURL, $order);
    }

    public function requestApi($url, $order)
    {
        $updata = array(
            'merchantId' => $this->config['merchantId'],
            'merOrderId' => $order['trade_no'],
            'txnAmt' => intval($order['amount'] * 100), //以分为单位
            'backUrl' => "{$_SERVER['REQUEST_SCHEME']}://{$_SERVER['HTTP_HOST']}/notify/npay",
            'frontUrl' => "{$_SERVER['REQUEST_SCHEME']}://{$_SERVER['HTTP_HOST']}/success.html",
            'subject' => 'subject',
            'content' => 'content',
            'userId' => '', //固定或者随机
            'gateway' => "alipayqr",
            // 'gateway' => 'alipayqrpersonal',
            // 'gateway' => 'alipayqrpersonalunfixed',
        );

        $paramsNeedSign = $this->npay_base64($updata, false);
        $signature = $this->npay_sign($paramsNeedSign, $this->config['signKey']);
        $updata['signature'] = $signature;
        $res = $this->http_post_request($url.'CreatePaymentAndWaitEscrow', http_build_query($updata));
        $res2 = json_decode($res, true);
        if (empty($res2['payLink'])) {
            throw new ParameterException([
                'msg'   => 'Channel API Error:[Request CreatePaymentAndWaitEscrow Fail].'
            ]);
        }

        return [
            'order_id' => $order['out_trade_no'],
            'pay_seq' => $order['trade_no'],
            'pay_url' => $res2['payLink'],
        ];
    }

    public function notify()
    {
        Log::write("Npay notify Request:\n\nURL: ".var_export($_REQUEST, true));

        return $this->verifyOrderNotify();
    }

    /**
     * 回调验签.
     *
     *
     * @return array
     *
     * @throws OrderException
     */
    private function verifyOrderNotify()
    {
        $returnArray = array( // 返回字段
            'merchantId' => $_REQUEST['merchantId'], // 商户ID
            'merOrderId' => $_REQUEST['merOrderId'], // 订单号
            'txnAmt' => $_REQUEST['txnAmt'], // 交易金额
            'respMsg' => $_REQUEST['respMsg'], // 交易信息
            'respCode' => $_REQUEST['respCode'], // 支付流水号
        );

        return array(
            'trade_no' => $_REQUEST['merOrderId'],
        );

        $sign = $this->npay_sign($returnArray, $this->config['signKey']);
        if ($sign == $_REQUEST['signature']) {//签名验证成功
            return array(
                'trade_no' => $_REQUEST['merOrderId'],
            );
        } else {
            exit('ok');
        }
    }

    public function npay_sign($params, $key)
    {
        ksort($params);
        $uri = urldecode(http_build_query($params));
        $uri = $uri.$key;
        $result = base64_encode(md5($uri, true));

        return $result;
    }

    public function npay_base64($params, $decode = true)
    {
        $need_base64_fields = [
                'subject',
                'content',
            ];
        foreach ($need_base64_fields as $k) {
            if (array_key_exists($k, $params)) {
                if ($decode) {
                    // $params[$k] = base64_decode($params[$k]);
                } else {
                    // $params[$k] = base64_encode($params[$k]);
                }
            }
        }

        return $params;
    }

    public function http_post_request($url, $params, $header = null)
    {
        $curl = curl_init($url);
        if ($header) {
            curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        }
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
        $res = curl_exec($curl);
        // curl失败
        if (0 !== curl_errno($curl)) {
            print_r(curl_error($curl));
            curl_close($curl);

            return false;
        }
        // curl成功
        curl_close($curl);

        return $res;
    }

    //回调开始
    public function callback()
    {
        $returnArray = array( // 返回字段
            'merchantId' => $_REQUEST['merchantId'], // 商户ID
            'merOrderId' => $_REQUEST['merOrderId'], // 订单号
            'txnAmt' => $_REQUEST['txnAmt'], // 交易金额
            'respMsg' => $_REQUEST['respMsg'], // 交易信息
            'respCode' => $_REQUEST['respCode'], // 支付流水号
            );
        $md5key = 'md5密钥';
        $sign = $this->npay_sign($returnArray, $md5key);

        if ($sign == $_REQUEST['signature']) {//签名验证成功
            exit('ok');
        } else {
            echo 'InnerError';
        }
    }
}
